package com.kasax.httpclient.core;

import com.kasax.httpclient.beans.Request;
import com.kasax.httpclient.core.inters.Call;
import com.kasax.httpclient.core.inters.Interceptor;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class KOkHttpClient {
    int conenctTimeout;
    int callTimeout;
    int writeTimeout;
    int readTimeout;
    // 连接池
    ConnectionPool connectionPool;

    // 分发器
    Dispatcher dispatcher;

    // 拦截器
    List<Interceptor> interceptors;

    // 重试次数
    int retrys;

    public KOkHttpClient(Builder builder) {
        this.conenctTimeout = builder.conenctTimeout;
        this.callTimeout = builder.callTimeout;
        this.readTimeout = builder.readTimeout;
        this.writeTimeout = builder.writeTimeout;
        this.connectionPool = builder.connectionPool;
        this.dispatcher = builder.dispatcher;
        this.interceptors = builder.interceptors;
        this.retrys = builder.retrys;
    }

    public ConnectionPool connectionPool() {
        return connectionPool;
    }

    public Dispatcher dispatcher() {
        return dispatcher;
    }

    public Call newCall(Request request) {
        return RealCall.newRealCall(this, request);
    }

    public int retrys() {
        return retrys;
    }

    public static class Builder {
        private int conenctTimeout;
        private int callTimeout;
        private int writeTimeout;
        private int readTimeout;
        // 连接池
        private ConnectionPool connectionPool = new ConnectionPool();

        // 分发器
        private Dispatcher dispatcher = new Dispatcher();

        // 拦截器
        private List<Interceptor> interceptors = new ArrayList<>();

        // 重试次数
        private int retrys = 3;

        public Builder conenctTimeout(int timeout, TimeUnit timeUnit) {
            this.conenctTimeout = Math.toIntExact(timeUnit.toMillis(timeout));
            return this;
        }

        public Builder callTimeout(int timeout, TimeUnit timeUnit) {
            this.callTimeout = Math.toIntExact(timeUnit.toMillis(timeout));
            return this;
        }

        public Builder writeTimeout(int timeout, TimeUnit timeUnit) {
            this.writeTimeout = Math.toIntExact(timeUnit.toMillis(timeout));
            return this;
        }

        public Builder readTimeout(int timeout, TimeUnit timeUnit) {
            this.readTimeout = Math.toIntExact(timeUnit.toMillis(timeout));
            return this;
        }

        public Builder addInterceptor(Interceptor interceptor) {
            this.interceptors = interceptors;
            return this;
        }

        public Builder retrys(int retrys) {
            this.retrys = retrys;
            return this;
        }

        public KOkHttpClient build() {
            return new KOkHttpClient(this);
        }
    }
}
